import re
import os

def clean_log_by_blocks(input_file, output_file=None):
    """
    使用状态机方法清理连续的队列错误块
    """
    if output_file is None:
        output_file = input_file
    
    with open(input_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    # 时间戳模式
    timestamp_pattern = r'\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\]'
    
    cleaned_lines = []
    in_queue_error_block = False
    current_block = []
    
    for line in lines:
        # 检查是否是时间戳行
        if re.match(timestamp_pattern, line):
            # 如果是队列错误时间戳
            if '队列错误' in line:
                if not in_queue_error_block:
                    # 开始新的队列错误块
                    in_queue_error_block = True
                    current_block = [line]
                else:
                    # 继续当前队列错误块
                    current_block.append(line)
            else:
                # 非队列错误的时间戳
                if in_queue_error_block:
                    # 结束队列错误块，丢弃该块
                    in_queue_error_block = False
                    current_block = []
                # 保留非队列错误行
                cleaned_lines.append(line)
        else:
            # 非时间戳行
            if in_queue_error_block:
                # 属于队列错误块的内容
                current_block.append(line)
            else:
                # 不属于队列错误块，保留
                cleaned_lines.append(line)
    
    # 写入清理后的内容
    with open(output_file, 'w', encoding='utf-8') as f:
        f.writelines(cleaned_lines)
    print(f"清理完成！原始文件有 {len(lines)} 行，清理后有 {len(cleaned_lines)} 行")
    print(f"清理后的文件保存为: {output_file}")

# 使用方法
if __name__ == "__main__":
    logdir = os.path.join(os.getcwd(), "log", "main")
    for vpath in os.listdir(logdir):
        clean_log_by_blocks(os.path.join(logdir, vpath))
        print("完成", vpath)